import React, { PureComponent } from 'react';
import styles from './style.less';
import iconfont from './fonts/iconfont.css';
import PropTypes from 'prop-types';

export default class SearchBox extends PureComponent {
  static defaultProps = {
    defaultValue: '',
    placeholder: '输入地址信息',
    city: '全国',
    top: 10,
    left: 10,
    onSearch: () => {},
  };

  static propTypes = {
    defaultValue: PropTypes.string,
    placeholder: PropTypes.string,
    city: PropTypes.string,
    onSearch: PropTypes.func,
    top: PropTypes.number,
    left: PropTypes.number,
  };

  constructor(props) {
    super(props);
    this.input = React.createRef();
    this.amap = props.__map__; // eslint-disable-line
    this.amap.plugin('AMap.Geocoder', () => {
      this.geocoder = new window.AMap.Geocoder();
    });
    this.state = {
      loading: false,
    };
  }

  onSearch = e => {
    this.search();
  };

  onEnter = e => {
    if (e.which === 13) {
      this.search();
    }
  };

  search() {
    const { city, onSearch } = this.props;
    this.setState({ loading: true });
    if (this.geocoder && this.input.current.value) {
      this.geocoder.setCity(city);
      this.geocoder.getLocation(this.input.current.value, (state, result) => {
        if (state === 'complete' && result.geocodes.length > 0) {
          this.setState({
            loading: false,
          });
        } else {
          this.setState({
            loading: false,
          });
        }
        if (typeof onSearch === 'function') onSearch(result.geocodes);
      });
    } else {
      this.setState({ loading: false });
    }
  }

  render() {
    if (!this.amap) return null;
    const { loading } = this.state;
    const { defaultValue, placeholder, top, left } = this.props;
    return (
      <div className={styles.searchbox} style={{ top, left }}>
        <img
          className={styles.logo}
          src=""
          draggable="false"
          alt="logo"
        />
        <div className={styles.iptbox}>
          <input
            ref={this.input}
            type="text"
            className={styles.searchipt}
            placeholder={placeholder}
            maxLength="256"
            autoComplete="off"
            defaultValue={defaultValue}
            onKeyDown={this.onEnter}
          />
          <div className={styles.searchbtn} onClick={this.onSearch}>
            {loading ? (
              <span
                className={`${iconfont.iconfont} ${iconfont.iconLoading} ${styles.iconLoading}`}
              ></span>
            ) : (
              <span
                className={`${iconfont.iconfont} ${iconfont.iconsousuo} ${styles.searchIcon}`}
              ></span>
            )}
          </div>
        </div>
      </div>
    );
  }
}
